/**
*  
* @Function 共享服务Controller 
* @ProjectName credit-data-platform 
* @PackageName com.py.credit.controller    
* @FileName ShareCustomizeController.java    
* @Date 2018年9月11日下午8:19:16
* @Author Min DongXv
* @Copyright (c) 2018, 金电联行 All Rights Reserved.   
*   
*/
package com.py.credit.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.DeptShareResourceEntity;
import com.py.credit.entity.ShareCustomizeEntity;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.ShareCustomizeFieldsEnum;
import com.py.credit.service.RemoteBaseService;
import com.py.credit.service.ShareCustomizeService;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.MapCache;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;

/**
 * 
 * @Function 共享服务Controller
 * @ClassName ShareCustomizeController
 * @Date 2018年9月11日 下午8:19:16
 * @Author Min DongXv
 * 
 */
@RestController
@RequestMapping(value = "/shareCustomize")
public class ShareCustomizeController extends BaseController {

	private static final String CUSTOMIZE_NAME = "ShareCustomizeId";

	private final static int NUM_1 = 1;

	private final static int NUM_4 = 4;

	@Autowired
	private RemoteBaseService remoteBaseService;

	@Autowired
	private ShareCustomizeService shareCustomizeService;

	@RequestMapping(value = "/getOptionalColums.json")
	public RestServiceResult<List<OptionalColumn>> getOptionalColums() {
		return new RestServiceResult<List<OptionalColumn>>(ShareCustomizeFieldsEnum.getOptionalColumns());
	}

	@RequestMapping(value = "/getAdvancedConditionColumns.json")
	public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns() {
		return new RestServiceResult<List<OptionalColumn>>(ShareCustomizeFieldsEnum.getAdvancedConditionColumns());
	}

	@RequestMapping(value = "/addShowColunms.json")
	public RestServiceResult<String> addShowColunms(@RequestParam(value = "columns", required = true) String[] columns,
			HttpServletRequest request) {
		RestServiceResult<String> result = new RestServiceResult<String>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("ShareCustomizeController#addShowColunms", "未获取到当前用户信息！");
				return result;
			}
			MapCache.set(userInfo.getId() + "_" + CUSTOMIZE_NAME, columns);
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		return new RestServiceResult<String>();
	}

	/**
	 * 
	 * @api {get} /shareCustomize/shareCustomizeList.json 获取共享定制列表
	 * @apiName shareCustomizeList
	 * @apiVersion 0.0.1
	 * @apiGroup 一站式查询
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":1,"data":[{"deptId":1,"managerId":1,"deptName":"工商部门","applyContent":null,"shareDate":1536818996000,"managerName":"超级管理员","updateTime":1536732605000,"customizeStatus":"R"}]}
	 */
	@RequestMapping(value = "/shareCustomizeList.json")
	public RestServiceResult<List<Map<String, Object>>> shareCustomizeList(HttpServletRequest request,
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page) {
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<>();
		String token = HttpServletHelper.getUserToken(request);
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("AchievementController#getAchievementCount", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		String[] configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + CUSTOMIZE_NAME);
		List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? ShareCustomizeFieldsEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
		try {
			// 获取列表数据
			List<Map<String, Object>> data = shareCustomizeService.shareCustomizeListByConditionForPage(showColumns,
					new String[] { "deptId", "managerId", "id" }, condition, page);
			if (!CollectionUtils.isEmpty(data)) {
				Set<Integer> userIds = new HashSet<Integer>(data.size());
				for (Map<String, Object> m : data) {
					if (null != m && m.containsKey("managerId") && null != m.get("managerId")) {
						userIds.add(Integer.parseInt(String.valueOf(m.get("managerId"))));
					}
				}
				remoteBaseService.matchUserName(data, result, token, userIds, "managerId", "managerName");
			}
			result.setCount(page.getTotalCount());
			result.setData(data);
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("ShareContentApplyController#shareCustomizeList",
					"获取共享定制列表数据异常！ERROR：" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("获取共享定制列表数据异常！");
			return result;
		}
	}

	/**
	 * 
	 * @api {get} /shareCustomize/updateShareCustomize.json 共享定制保存
	 * @apiName shareCustomize
	 * @apiVersion 0.0.1
	 * @apiGroup 一站式查询
	 * @apiParam {long} id
	 * @apiParam {long} deptId
	 * @apiParam {String} shareDate
	 * @apiParam {String} customizeStatus
	 * @apiParam {String} resource
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@RequestMapping(value = "/updateShareCustomize.json")
	public RestServiceResult<Object> shareCustomize(HttpServletRequest request,
			@RequestParam(value = "id", defaultValue = "", required = true) Long id,
			@RequestParam(value = "deptId", defaultValue = "", required = true) long deptId,
			@RequestParam(value = "shareDate", defaultValue = "", required = true) String shareDate,
			@RequestParam(value = "customizeStatus", defaultValue = "", required = true) String customizeStatus,
			@RequestParam(value = "resource", defaultValue = "", required = true) String resource) {
		RestServiceResult<Object> result = new RestServiceResult<>();
		String token = HttpServletHelper.getUserToken(request);
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("AchievementController#getAchievementCount", "未获取到当前用户信息！");
				return result;
			}
			// 只有管理员才能进行操作
			if (NUM_1 == userInfo.getUserType() || NUM_4 == userInfo.getUserType()) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("权限不足，只有管理员才能进行此操作！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		// 资源必选
		if (null != id && StringUtils.isNotBlank(resource)) {
			try {
				List<String> resources = JSON.parseArray(resource, String.class);
				List<DeptShareResourceEntity> resourceInfo = new ArrayList<DeptShareResourceEntity>(resources.size());
				DeptShareResourceEntity e = null;
				for (String s : resources) {
					e = new DeptShareResourceEntity();
					e.setDeptId(deptId);
					e.setResourceId(s);
					resourceInfo.add(e);
				}
				// 更新共享定制
				shareCustomizeService.updateShareCustomize(id, shareDate, userInfo.getId(), customizeStatus,
						resourceInfo, deptId);
				return result;
			} catch (Exception e) {
				ExceptionLogger.error("ShareContentApplyController#updateShareCustomize",
						"更新共享定制数据异常！ERROR：" + e.getMessage(), e);
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("更新共享定制数据异常！");
				return result;
			}
		} else {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("请选择资源表数据");
			return result;
		}
	}

	/**
	 * 
	 * @api {get} /shareCustomize/shareCustomize.json 共享定制详情
	 * @apiName shareCustomizeDetail
	 * @apiVersion 0.0.1
	 * @apiGroup 一站式查询
	 * @apiParam {Long} deptId 部门ID
	 * @apiParamExample {json} 请求参数示例 {"deptId":1}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@RequestMapping(value = "/shareCustomize.json")
	public RestServiceResult<ShareCustomizeEntity> shareCustomizeDetail(
			@RequestParam(value = "deptId", defaultValue = "", required = true) long deptId) {
		RestServiceResult<ShareCustomizeEntity> result = new RestServiceResult<>();
		try {
			ShareCustomizeEntity data = shareCustomizeService.shareCustomizeDetail(deptId);
			result.setData(data);
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("ShareContentApplyController#shareCustomizeDetail",
					"获取共享定制数据异常！ERROR：" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("获取共享定制数据异常！");
			return result;
		}
	}

	/**
	 * 
	 * @api {get} /shareCustomize/export.json 共享定制导出
	 * @apiName export
	 * @apiVersion 0.0.1
	 * @apiGroup 一站式查询
	 * @apiParam {String} condition 查询条件
	 * @apiParam {String} columnEN 导出列英文名
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@RequestMapping(value = "/export")
	public RestServiceResult<List<Map<String, Object>>> export(
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition,
			@RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN, Page page,
			HttpServletResponse response, HttpServletRequest request) {
		page.setLimit(1000);
		List<String> showColumns = JSONArray.parseArray(columnEN, String.class);
		List<OptionalColumn> optionalColumns = ShareCustomizeFieldsEnum.getOptionalColumns();
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		String token = HttpServletHelper.getUserToken(request);
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("ShareContentApplyController#export", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		try {
			// 填充部门信息
			List<Map<String, Object>> data = shareCustomizeService.shareCustomizeListByConditionForPage(showColumns,
					new String[] { "deptId", "managerId" }, condition, page);
			if (!CollectionUtils.isEmpty(data)) {
				Set<Integer> userIds = new HashSet<Integer>(data.size());
				for (Map<String, Object> m : data) {
					if (null != m && m.containsKey("managerId") && null != m.get("managerId")) {
						userIds.add(Integer.parseInt(String.valueOf(m.get("managerId"))));
					}
				}
				remoteBaseService.matchUserName(data, result, token, userIds, "managerId", "managerName");
			}
			ExcelUtil.downloadExcel(response, data, "共享定制", "共享定制", showColumns, optionalColumns);
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("共享定制导出异常，请稍后再试！");
			ExceptionLogger.error("共享定制导出异常！", e.getMessage(), e);
			return result;
		}
	}
}
